package com.trumeen.immichgallery.ui.navigation

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.trumeen.immichgallery.ui.screen.FullscreenImageScreen
import com.trumeen.immichgallery.ui.screen.PersonSelectionScreen
import com.trumeen.immichgallery.ui.screen.SettingsScreen
import com.trumeen.immichgallery.viewmodel.ConnectionStatus
import com.trumeen.immichgallery.viewmodel.MainViewModel

@Composable
fun AppNavigation(
    navController: NavHostController = rememberNavController()
) {
    val mainViewModel: MainViewModel = hiltViewModel()

    // 监听认证状态
    val connectionStatus by mainViewModel.connectionStatus.collectAsState()

    // 检查认证状态并导航
    LaunchedEffect(connectionStatus) {
        when (connectionStatus) {
            ConnectionStatus.CONNECTED -> {
                // 如果已认证，确保在主屏幕
                if (navController.currentDestination?.route != Screen.FullscreenImage) {
                    navController.navigate(Screen.FullscreenImage) {
                        popUpTo(0) // 清空返回栈
                    }
                }
            }
            else -> {
                // 如果未认证，跳转到设置页面
                if (navController.currentDestination?.route != Screen.Settings) {
                    navController.navigate(Screen.Settings) {
                        popUpTo(0) // 清空返回栈
                    }
                }
            }
        }
    }

    NavHost(
        navController = navController,
        startDestination = Screen.FullscreenImage // 初始路由，但会被LaunchedEffect覆盖
    ) {
        composable(Screen.FullscreenImage) {
            FullscreenImageScreen(navController = navController)
        }
        composable(Screen.Settings) {
            SettingsScreen(navController = navController)
        }
        composable(Screen.PersonSelection) {
            PersonSelectionScreen(navController = navController)
        }
    }
}

object Screen {
    const val FullscreenImage = "fullscreen_image"
    const val Settings = "settings"
    const val PersonSelection = "person_selection"
}